package com.xzq.hm;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/18 21:23
 * @Version 1.0.0
 **/
public class NettyServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                //创建NioEventLoopGroup, 简单理解为  线程池+Selector
                .group(new NioEventLoopGroup())
                //创建服务Socket实现类，其中NioServerSocketChannel表示基于NIO的服务端实现
                .channel(NioServerSocketChannel.class)
                /**
                 * 叫childHandler，是接下来添加的处理器都是给SocketChannel用的，而不是给
                 * ServerSocketChannel.ChannelInitializer处理器，它的作用是待客户端
                 * SocketChannel建立连接后，执行initChannel以便添加更多的处理器
                 */
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //SocketChannel的处理器，解码 ByteBuf=>String
                        ch.pipeline().addLast(new StringDecoder());
                        //SocketChannel的业务处理器，使用上一个处理器的处理结果
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

                            }
                        });
                    }
                    //ServerSocketChannel绑定的监听端口
                }).bind(9999);
    }
}
